// 根路由配置
import Vue from 'vue'
import Router from 'vue-router'
import store from '../stores'

Vue.use(Router)

// 路由空时报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 动态引入路由
const routes = []
const context = require.context('../routers', true, /\/[\w]+\.(js|ts)$/)
context.keys().forEach(_ => {
  const path = _.replace('./', '')
  let routeName = path.replace('.js', "")
  // console.log(routeName)
  // console.log(require('./' + path)[routeName].path)
  if (routeName != 'index') {
    routes.push(require('./' + path)[routeName])
  }
})

// console.log(routes)

const routers = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    ...routes,
  ]
})

const publicURL = [
  'apply_agreement',
  'forget_password',
  'agent_apply',
  'login',
  '/'
]

routers.beforeEach((to, from, next) => {
  // console.log("【 路由 From 】：", from)
  // console.log("【 路由 To 】：", to)

  // 判断是否登录
  let httpToken = localStorage.getItem('httpToken')
  if (publicURL.indexOf(to.name) == -1) {
    if (!httpToken && to.name != 'login') {
      routers.replace({
        path: '/login'
      })
      return false
    }
  }

  if (to.name != null) {

    if (to.meta) {
      let navInfo = to.meta

      // 修改html标题
      document.title = navInfo.title + ' - TIMELESS 分销商城'
      store.commit('setNavInfo', navInfo)
    }
    // store.commit('setUserInfoFromLocalStorage')

    next()
  } else if (to.path == '/') {
    routers.replace({
      path: '/login'
    })
  } else {
    next({
      path: '/not_found',
      query: {}
    })
  }

})

export default routers